package cn.wang.cart.interceptor;


import cn.wang.auth.pojo.UserInfo;
import cn.wang.auth.utils.JwtUtils;
import cn.wang.cart.config.JwtConfig;
import cn.wang.common.utils.CookieUtils;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Data
@Component
public class CartInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private JwtConfig jwtConfig;

    // threadLocal中存储的每一个信息都和当前的线程进行了绑定
    private static final ThreadLocal<UserInfo> THREAD_LOCAL = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取token
        String token = CookieUtils.getCookieValue(request, jwtConfig.getTokenName());
        // 根据token获取用户信息
        UserInfo userInfo = JwtUtils.getInfoFromToken(token, jwtConfig.getPublicKey());
        // 将userinfo存放进入到当前线程中
        THREAD_LOCAL.set(userInfo);
        return true; // false 表示进行拦截, true表示不进行拦截
    }


    // 在拦截执行完后, 将userInfo从线程中移除
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 释放threadlocal中的资源
        THREAD_LOCAL.remove();
    }
    public static UserInfo getUserInfo(){
        return THREAD_LOCAL.get();
    }
}
